#include "login.h"

Login::Login()
{
    userindex = 0;
    attempt = 3;
}

std::string Login::login()
{
    std::fstream login_file;
    login_file.open(LG_PATH, std::ios::in);
    if(!login_file.is_open())
    {
        system("echo \"root 004429 Administrator\" > ../info/login_info.txt");
        login_file.open(LG_PATH, std::ios::in);
    }
    std::string temp, tempusername, temppassword, all;
    if(!login_file.is_open())
    {
        login_file.close(); 
        return "";
    }
    while(attempt)
    {
        drawLogin_Info();
        moveCursor('u', 6);
        moveCursor('r',11); 
        password.clear();
        username.clear();
        temp.clear();
        tempusername.clear();
        userindex = 0;
        username = readCommand();
        moveCursor('d', 1);
        moveCursor('r',10); 
        char *p = getpass("");
        
        for(int i = 0; i < strlen(p); i++)
        {
            password.append(1, p[i]);
        }
        -- attempt;
        login_file.close();
        info = readFile(LG_PATH);
        for(int i = 1; i < info[1].size(); i++)
        {
            if(username == info[1][i] && password == info[2][i])
            {
                return username;
            }
        }
        if(attempt > 0)
        {
            system("clear");
            std::cout << "\n\n\t\t\033[01;31mFail To Login." << std::endl;
            sleep(2);
            system("clear");
            std::cout << "\n\n\t\t" << attempt << " Attempts Left\033[0m" << std::endl;
            sleep(2);
        }
    }

    return "";
}


void Login::drawLogin_Info()
{
    system("clear");
    std::vector<std::string> lines;
    lines.clear();
    lines.push_back("------------------------------------------------------------");
    lines.push_back("|                  Student Manage System                   |");
    lines.push_back("------------------------------------------------------------");
    lines.push_back("|                          Login                           |");
    lines.push_back("------------------------------------------------------------");
    lines.push_back("|User name:                                                |");
    lines.push_back("|                                                          |");
    lines.push_back("|Password:                                                 |");
    lines.push_back("------------------------------------------------------------");
    lines.push_back("|Press Enter to continue                                   |");
    lines.push_back("------------------------------------------------------------");
    for(auto a : lines) std::cout << "\033[01;35m" << a << "\033[0m" << std::endl;
}